package com.villaday.idf.util;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentActivity;

import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import java.math.RoundingMode;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Locale;
import java.util.UUID;

import static android.text.TextUtils.isEmpty;


/**
 * 获取手机相关信息
 */
public class PhoneUtil {
    /**
     * 获取当前应用程序的包名
     *
     * @param context 上下文对象
     * @return 返回包名
     */
    public static String getAppProcessName(Context context) {
        //当前应用pid
        int pid = android.os.Process.myPid();
        //任务管理类
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        //遍历所有应用
        List<ActivityManager.RunningAppProcessInfo> infos = manager.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo info : infos) {
            if (info.pid == pid)//得到当前应用
                return info.processName;//返回包名
        }
        return "";
    }

    /**
     * 获取手机屏幕宽度
     */
    public static int getPhoneWidth(Context context) {
        return context.getResources().getDisplayMetrics().widthPixels;
    }

    /**
     * 获取手机屏幕高度
     */
    public static int getPhoneHeight(Context context) {
        return context.getResources().getDisplayMetrics().heightPixels;
    }

    /**
     * 获取控件高度
     */
    public static int getWidgetHeight(View v) {
        int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        v.measure(w, h);
        return v.getMeasuredHeight();
    }

    /**
     * 获取控件宽度
     */
    public static int getWidgetWidth(View v) {
        int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        v.measure(w, h);
        return v.getMeasuredWidth();
    }

    /**
     * dp 转 px
     */
    public static int dp2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * px 转 dp
     */
    public static int px2dp(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 获取手机ip
     */
    public static String getLocalIpAddress() {
        try {
            for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface ni = (NetworkInterface) en.nextElement();
                for (Enumeration netAddress = ni.getInetAddresses(); netAddress.hasMoreElements(); ) {
                    InetAddress inetAddress = (InetAddress) netAddress.nextElement();
                    if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取App名称
     */
    public static String getAppName(Context context) {
        String appName = null;
        try {
            PackageManager packageManager = context.getPackageManager();
            ApplicationInfo info = packageManager.getApplicationInfo(context.getPackageName(), 0);
            appName = (String) packageManager.getApplicationLabel(info);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return appName;
    }

    /**
     * 获取App版本号
     */
    public static String getAppVersion(Context context) {
        String versionName = null;
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            versionName = packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionName;
    }

    public static boolean isAppInstalled(Context context, String packageName) {
        try {
            context.getPackageManager().getApplicationInfo(packageName, 0);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }
    }

    /**
     * 是否需要更新
     * return  0 -- 不需要更新、1 -- 需要更新、2 -- 需要强制更新
     */
    public static int isNeedUpdate(String thisVersion, String newVersion) {
        try {
            if (thisVersion.equals(newVersion)) {
                return 0;
            }
            int times = 100;//倍率
            float currTimes;//当前倍数
            float v1 = 0;//当前版本计算值
            float v2 = 0;//服务器版本计算值
            currTimes = 0.01F;
            String[] ver1 = thisVersion.split("\\.");
            for (int i = ver1.length - 1; i >= 0; i--) {
                v1 += Integer.parseInt(ver1[i]) * currTimes;
                currTimes *= times;
            }
            currTimes = 0.01F;
            String[] ver2 = newVersion.split("\\.");
            if (Integer.parseInt(ver1[0]) < Integer.parseInt(ver2[0])) {//有重大更新
                return 2;
            }
            for (int i = ver1.length - 1; i >= 0; i--) {
                v2 += Integer.parseInt(ver2[i]) * currTimes;
                currTimes *= times;
            }
            if (v2 > v1) {
                return 1;
            } else {
                return 0;
            }
        } catch (Exception e) {
            if (!thisVersion.equals(newVersion)) {
                return 1;
            } else {
                return 0;
            }
        }
    }

    /**
     * 更新购物车上的红点
     */
//    public static void upCartDot(Application application, CircleTextView circleView) {
//        int count = ((AppContext) application).getCartCount();
//        if (count > 0) {
//            circleView.setText(count + "");
//            circleView.setVisibility(View.VISIBLE);
//        } else {
//            circleView.setVisibility(View.INVISIBLE);
//        }
//    }

    /**
     * 处理头像null情况
     */
    public static Uri getHead(String head) {
        if (isEmpty(head)) {
            return Uri.parse(Constant.URL.DefaultHeadImg);
        } else {
//            return Uri.parse(Constant.URL.BaseImg + head);
            return Uri.parse(head);
        }
    }

    /**
     * 处理昵称null情况
     */
    public static String getAlias(String alias, String mobile) {
        if (!isEmpty(alias)) {
            return alias;
        } else {
            return getMobile(mobile);
        }
    }

    /**
     * 手机号加*
     */
    public static String getPassport(String passport) {
        if (isEmpty(passport)) {
            return "****";
        } else {
            if (passport.length() >= 7) {
                return passport.substring(0, 3) + "****" + passport.substring(passport.length() - 2);
            } else {
                return "****";
            }
        }
    }


    /**
     * 手机号加*
     */
    public static String getMobile(String mobile) {
        if (isEmpty(mobile)) {
            return "****";
        } else {
            if (mobile.length() >= 7) {
                return mobile.substring(0, 3) + "****" + mobile.substring(7, mobile.length());
            } else {
                return mobile + "****";
            }
        }
    }

    public static String getIDCode(String IDCode) {
        String code = "";
        if (isEmpty(IDCode)) {
            return "****";
        } else {

            code = IDCode.substring(0, 6);
            for (int i = 0; i < 4; i++) {
                code = code + "*";
            }

            code = code + IDCode.substring(IDCode.length() - 8, IDCode.length());

            return code;

        }
    }

    /**
     * 邮箱用****号隐藏前面的字母
     *
     * @param email 邮箱账号
     * @return
     */
    public static String settingemail(String email) {
        String emails = email.replaceAll("(\\w?)(\\w+)(\\w)(@\\w+\\.[a-z]+(\\.[a-z]+)?)", "$1****$3$4");
        return emails;
    }


    /**
     * 身份证号用****号隐藏前面的字母
     *
     * @param idCard 身份证号
     * @return
     */
    public static String settingID(String idCard) {
        String idCardHide = idCard.replaceAll("(\\d{1})\\d{16}(\\w{1})", "$1****************$2");
        return idCardHide;
    }




    /*public static String getLocalMobile(Context context) {
        UserInfoEntity.DataEntity userInfo = getUserInfo(context);
        if (userInfo != null) {
            return userInfo.getMobile();
        }
        return null;
    }*/

    /**
     * 本地缓存是否可用
     */
    public static boolean isUrlCacheValid(Context context, String url) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        if (isEmpty(CacheUtil.getUrlCache(url))) {
            return false;
        } else {
            try {
                SharedPreferences isFirst = context.getSharedPreferences("isFirst", context.MODE_PRIVATE);
                String lastModifyTime = isFirst.getString("LastAddressModifyTime", sdf.format(new Date()));
                long cacheModifyTime = CacheUtil.getUrlCacheModifyTime(url);
                if (cacheModifyTime > sdf.parse(lastModifyTime).getTime()) {
                    return true;
                } else {
                    return false;
                }
            } catch (Exception e) {
                return false;
            }
        }
    }

    /**
     * 弹出键盘
     */
    public static void showKeyboard(final View v) {
        v.post(new Runnable() {
            @Override
            public void run() {
                InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
            }
        });
    }

    /**
     * 隐藏键盘
     */
    public static void hideKeyboard(View v) {
        InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive()) {
            imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
        }
    }

    /**
     * 复制到剪贴板
     */
    public static void copyBoard(Context context, String str) {
        ClipboardManager boardManager = (ClipboardManager) context.getSystemService(context.CLIPBOARD_SERVICE);
        boardManager.setPrimaryClip(ClipData.newPlainText(null, str));
        ToastUtil.initToast(context, "复制成功！");
    }

    /**
     * 判断EditText输入是否错误 -- 判断2个字符
     */
    public static void isEditError2(String text, EditText editText) {
        if (!isEmpty(text)) {
            if (text.contains("\"")) {
                editText.setError(Constant.Strings.ErrorTips1);
            }
            if (text.contains("\\")) {
                editText.setError(Constant.Strings.ErrorTips2);
            }
        } else {
            editText.setError(null);
        }
    }

    /**
     * 判断EditText输入是否错误 -- 判断2个字符 带删除按钮
     */
    public static void isEditError2WithDel(String text, EditText editText, View delBtn) {
        if (!isEmpty(text)) {
            if (text.contains("\"")) {
                editText.setError(Constant.Strings.ErrorTips1);
            }
            if (text.contains("\\")) {
                editText.setError(Constant.Strings.ErrorTips2);
            }
            delBtn.setVisibility(View.VISIBLE);
        } else {
            editText.setError(null);
            delBtn.setVisibility(View.GONE);
        }
    }

    /**
     * 判断EditText输入是否错误 -- 判断2个字符 带删除按钮、带可输入字数
     */
    public static void isEditError2WithDelWithNum(String text, EditText editText, View delBtn, TextView tvLimit) {
        if (!isEmpty(text)) {
            if (text.contains("\"")) {
                editText.setError(Constant.Strings.ErrorTips1);
            }
            if (text.contains("\\")) {
                editText.setError(Constant.Strings.ErrorTips2);
            }
            delBtn.setVisibility(View.VISIBLE);
            tvLimit.setText((140 - text.length()) + "");
        } else {
            editText.setError(null);
            delBtn.setVisibility(View.GONE);
            tvLimit.setText(140 + "");
        }
    }

    /**
     * 判断EditText输入是否错误 -- 判断3个字符
     */
    public static void isEditError3(String text, EditText editText) {
        if (!isEmpty(text)) {
            isEditError2(text, editText);
            if (text.contains("|")) {
                editText.setError(Constant.Strings.ErrorTips3);
            }
        } else {
            editText.setError(null);
        }
    }

    /**
     * 判断EditText输入是否错误 -- 判断4个字符
     */
    public static void isEditError4(String text, EditText editText) {
        if (!isEmpty(text)) {
            isEditError3(text, editText);
            if (text.contains("_")) {
                editText.setError(Constant.Strings.ErrorTips4);
            }
        } else {
            editText.setError(null);
        }
    }

    /**
     * 数字转换为二位小数
     */
    public static String formatDecimal(double d, int pointNum) {
        StringBuffer format = new StringBuffer("0");
        for (int i = 0; i < pointNum; i++) {
            if (i == 0) {
                format.append(".");
            }
            format.append("0");
        }
        return new DecimalFormat(format.toString()).format(d);
    }

    /**
     * 格式化当前时间
     */
    public static String formatDate() {
        SimpleDateFormat sdf24H = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS", Locale.getDefault());
        return sdf24H.format(new Date());
    }

    /**
     * 获取尾数
     */
    public static String getEndNum(String s, int endNum) {
        if (!isEmpty(s) && s.length() > endNum) {
            return s.substring(s.length() - endNum);
        }
        return s;
    }

    /**
     * 处理金额  超过1万用简写
     */
    public static String handleBalance(String balance, int pointNum) {
        double d = Double.parseDouble(balance);
        if (d <= 10000) {
            return formatDecimal(d, pointNum);
        } else {
/*
            return formatDecimal(d / 10000, pointNum) + "万";
*/
            return formatDecimal(d, pointNum);

        }
    }

    public static String handleBalance2(String balance, int pointNum) {
        double d = Double.parseDouble(balance);
        if (d < 10000) {
            return formatDecimal(d, pointNum);
        } else {
            return formatDecimal(d / 10000, pointNum) + "万";
        }
    }


    public static String handleDecimal2(String balance) {
        double d = Double.parseDouble(balance);
        DecimalFormat formater = new DecimalFormat("#0.00");
        formater.setRoundingMode(RoundingMode.FLOOR);
        return formater.format(d);
    }

    public static String handleDecimal2NO(String balance) {
        double d = Double.parseDouble(balance);
        DecimalFormat formater = new DecimalFormat("#0.##");
        formater.setRoundingMode(RoundingMode.FLOOR);
        return formater.format(d);
    }

    /**
     * 处理日期
     */
    public static String handleTime(String time) {
        if (!isEmpty(time) && time.endsWith(".000")) {
            return time.substring(0, time.lastIndexOf("."));
        }
        return time;
    }

    /**
     * 拼接收货地址
     */
    /*public static String stitchAddress(AddressEntity.DataEntity d){
        String address = d.getProvince() + "_" + d.getCity() + "_" + d.getCounty() + "_" + d.getAddress();
        return d.getRealName() + "|" + d.getMobile() + "|" + d.getZipCode() + "|" + address;
    }*/
   /* public static String getLocalMobile(Context context) {
        UserInfoEntity.DataEntity userInfo = getUserInfo(context);
        if (userInfo != null) {
            return userInfo.getMobile();
        }
        return null;
    }*/

    /*  *//**
     * 获取本地的用户信息
     *//*
    public static UserInfoEntity.DataEntity getUserInfo(Context context) {
        SharedPreferences userInfo = context.getSharedPreferences("userInfo", context.MODE_PRIVATE);
        String info = userInfo.getString("UserInfo", null);
        if (info != null) {
            try {
                info = DesUtil.decrypt(info, DesUtil.LOCAL_KEY);
                UserInfoEntity infoEntity = new Gson().fromJson(info, UserInfoEntity.class);
                return infoEntity.getData();
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
        return null;
    }*/


    /**
     * 转换为字符串日期
     */
    public static String getDateOfNum(int year, int month, int day) {
        DecimalFormat format2 = new DecimalFormat("00");
        return year + "-" + format2.format(month) + "-" + format2.format(day);
    }

    /*
     * 渠道标志为：
     * 1，andriod（a）
     *
     * 识别符来源标志：
     * 1， wifi mac地址（wifi）；
     * 2， IMEI（imei）；
     * 3， 序列号（sn）；
     * 4， id：随机码。若前面的都取不到时，则随机生成一个随机码，需要缓存。
     *
     * @param context
     * @return
     */
    public static String getDeviceId(Context context) {
        StringBuilder deviceId = new StringBuilder();
        // 渠道标志
        deviceId.append("a");
        try {
            //wifi mac地址
            WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            WifiInfo info = wifi.getConnectionInfo();
            String wifiMac = info.getMacAddress();
            if (!isEmpty(wifiMac)) {
                deviceId.append("wifi");
                deviceId.append(wifiMac);
                Log.e("getDeviceId : ", deviceId.toString());
                return deviceId.toString();
            }
            //IMEI（imei）
            TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            String imei = tm.getDeviceId();
            if (!isEmpty(imei)) {
                deviceId.append("imei");
                deviceId.append(imei);
                Log.e("getDeviceId : ", deviceId.toString());
                return deviceId.toString();
            }
            //序列号（sn）
            String sn = tm.getSimSerialNumber();
            if (!isEmpty(sn)) {
                deviceId.append("sn");
                deviceId.append(sn);
                Log.e("getDeviceId : ", deviceId.toString());
                return deviceId.toString();
            }
            //如果上面都没有， 则生成一个id：随机码
            String uuid = getUUID(context);
            if (!isEmpty(uuid)) {
                deviceId.append("id");
                deviceId.append(uuid);
                Log.e("getDeviceId : ", deviceId.toString());
                return deviceId.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
            deviceId.append("id").append(getUUID(context));
        }
        Log.e("getDeviceId : ", deviceId.toString());
        return deviceId.toString();
    }

    /**
     * 得到全局唯一UUID
     */
    public static String getUUID(Context context) {
        SharedPreferences mShare = context.getSharedPreferences("sysCacheMap", context.MODE_PRIVATE);
        String uuid = null;
        if (mShare != null) {
            uuid = mShare.getString("uuid", "");
        }
        if (isEmpty(uuid)) {
            uuid = UUID.randomUUID().toString();
            SharedPreferencesUtil.saveData(context, "sysCacheMap", "uuid", uuid);
        }
        Log.e("UUID", "getUUID : " + uuid);
        return uuid;
    }

    /**
     * 创建指定数量的随机字符串
     *
     * @param numberFlag 是否是数字
     * @param length
     * @return String
     */
    public static String createRandom(boolean numberFlag, int length) {
        String retStr = "";
        String strTable = numberFlag ? "1234567890" : "1234567890abcdefghijkmnpqrstuvwxyz";
        int len = strTable.length();
        boolean bDone = true;
        do {
            retStr = "";
            int count = 0;
            for (int i = 0; i < length; i++) {
                double dblR = Math.random() * len;
                int intR = (int) Math.floor(dblR);
                char c = strTable.charAt(intR);
                if (('0' <= c) && (c <= '9')) {
                    count++;
                }
                retStr += strTable.charAt(intR);
            }
            if (count >= 2) {
                bDone = false;
            }
        } while (bDone);
        return retStr;
    }

    /**
     * SHA加密
     *
     * @param strSrc 明文
     * @return 加密之后的密文
     */
    public static String SHA256(String strSrc) {
        MessageDigest md = null;
        String strDes = null;
        byte[] bt = strSrc.getBytes();
        try {
            md = MessageDigest.getInstance("SHA-256");// 将此换成SHA-1、SHA-512、SHA-384等参数
            md.update(bt);
            strDes = bytes2Hex(md.digest()); // to HexString
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
        return strDes;
    }

    /**
     * byte数组转换为16进制字符串
     *
     * @param bts 数据源
     * @return 16进制字符串
     */
    public static String bytes2Hex(byte[] bts) {
        String des = "";
        String tmp = null;
        for (int i = 0; i < bts.length; i++) {
            tmp = (Integer.toHexString(bts[i] & 0xFF));
            if (tmp.length() == 1) {
                des += "0";
            }
            des += tmp;
        }
        return des;
    }


    /**
     * 时间戳转化成日期
     */
    public static String stampToDate(String s) {
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日");
        long lt = new Long(s);
        Date date = new Date(lt);
        res = simpleDateFormat.format(date);
        return res;
    }

    //dip转像素
    public static int DipToPixels(Context context, int dip) {
        final float SCALE = context.getResources().getDisplayMetrics().density;
        float valueDips = dip;
        int valuePixels = (int) (valueDips * SCALE + 0.5f);
        return valuePixels;
    }

    //像素转dip
    public static float PixelsToDip(Context context, int Pixels) {
        final float SCALE = context.getResources().getDisplayMetrics().density;
        float dips = Pixels / SCALE;
        return dips;
    }


    //引入外部字体
    public static void setExternalFont(Context context, TextView textView, boolean isBold) {
        //得到AssetManager
        AssetManager mgr = context.getAssets();
//根据路径得到Typeface
        Typeface tf = Typeface.createFromAsset(mgr, "DIN-MEDIUM.OTF");
        textView.setTypeface(tf);

        if (isBold) {
            textView.getPaint().setFakeBoldText(true);
        }

    }

    // 将px值转换为sp值
    public static int px2sp(Context context, float pxValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5f);
    }




    // 将px值转换为sp值
    public static int sp2px(Context context, float pxValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue * fontScale + 0.5f);
    }

    public static boolean isVisible(AppCompatActivity context, View tagView) {
        if (tagView != null) {
            Point p = new Point();
            context.getWindowManager().getDefaultDisplay().getSize(p);
            int screenWidth = p.x;
            int screenHeight = p.y;
            Rect rect = new Rect(0, 0, screenWidth, screenHeight);
            int[] location = new int[2];
            tagView.getLocationInWindow(location);
            if (tagView.getLocalVisibleRect(rect)) {
// 控件在屏幕可见区域
                return true;


            } else {
// 控件已不在屏幕可见区域（已滑出屏幕）
                return false;
            }
        } else {
            return false;
        }


    }

    public static boolean isVisible(FragmentActivity context, View tagView) {
        Point p = new Point();
        context.getWindowManager().getDefaultDisplay().getSize(p);
        int screenWidth = p.x;
        int screenHeight = p.y;
        Rect rect = new Rect(0, 0, screenWidth, screenHeight);
        int[] location = new int[2];
        tagView.getLocationInWindow(location);
        if (tagView.getLocalVisibleRect(rect)) {
// 控件在屏幕可见区域
            return true;


        } else {
// 控件已不在屏幕可见区域（已滑出屏幕）
            return false;
        }

    }

    public static int getHeight(View view) {
        int width = View.MeasureSpec.makeMeasureSpec(0,
                View.MeasureSpec.UNSPECIFIED);
        int height = View.MeasureSpec.makeMeasureSpec(0,
                View.MeasureSpec.UNSPECIFIED);
        view.measure(width, height);
        view.getMeasuredWidth(); // 获取宽度
        view.getMeasuredHeight(); // 获取高度
//        LogUtil.jLog().e(rlFhwsdInstall.getMeasuredHeight() + "  " + rlFhwsdInstall.getMeasuredWidth());
        return view.getMeasuredHeight();
    }

    //如果输入法在窗口上已经显示，则隐藏，反之则显示
    public static void showOrHide(Context context) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    //view为接受软键盘输入的视图，SHOW_FORCED表示强制显示
    public static void showOrHide(Context context, View view) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        //  imm.showSoftInput(view, InputMethodManager.SHOW_FORCED);//SHOW_FORCED表示强制显示
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0); //强制隐藏键盘
    }

    //调用隐藏系统默认的输入法
    public static void showOrHide(Context context, Activity activity) {
        ((InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE))
                .hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
    }

    //获取输入法打开的状态
    public static boolean isShowing(Context context) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        return imm.isActive();//isOpen若返回true，则表示输入法打开
    }

}
